// 现有字体库，OpenCC st2和t2s下载txt使用
// 为提升速度，txt有所删减。
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead, BufReader};


// 从文件中加载简繁转换规则
fn load_conversion_rules(file_path: &str) -> io::Result<HashMap<String, String>> {
    let file = File::open(file_path)?;
    let reader = BufReader::new(file);
    let mut rules = HashMap::new();

    for line in reader.lines() {
        let line = line?;
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() == 2 {
            let traditional = parts[0].to_string();
            let simplified = parts[1].to_string();
            rules.insert(traditional, simplified);
        }
    }

    Ok(rules)
}

// 执行简繁转换
fn convert(text: &str, rules: &HashMap<String, String>) -> String {
        let input = text.to_string();
        let result = rules.get(&input).unwrap_or(&input);
        return result.to_string();
}

pub fn converter(input: &str, tp: &str) -> String {
    let st_rules = load_conversion_rules("STPhrases.txt").expect("Failed to load STPhrases.txt");
    let ts_rules = load_conversion_rules("TSPhrases.txt").expect("Failed to load TSPhrases.txt");

    let result = match tp{
        "s2t" =>{
            let traditional_output = convert(input, &st_rules);
            return traditional_output;
        }
        "t2s" =>{
            let simplified_output = convert(input, &ts_rules);
            return simplified_output;
        }
        _ => input.to_string(),
    };
    result
}
